package com.example.demo.controller;

import com.example.demo.Customer;
import com.example.demo.service.CvsService;
import com.example.demo.service.ExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;

/**
 * @author luoyong
 * @since 1.1-baseline
 */
@RestController
public class CvsController {
    @Autowired
    CvsService cvsService;

    @RequestMapping("/download")
    public String downloadCvs(Integer[] ids,HttpServletResponse response) {
        List<Customer> customerList = getData(ids);
        if (customerList.size() == 0 ){

            return "failure";
        }
        String sTitle = "编号,姓名,年龄,时间";
        String fName = "customer_";
        String mapKey = "id,name,age,date";
        List<Map<String,Object>> dataList = new ArrayList<>();
        Map<String,Object> map = null ;
        for (Customer customer : customerList) {
            map = new HashMap<String, Object>();
            map.put("id",customer.getId());
            map.put("name",customer.getName());
            map.put("age",customer.getAge());
            map.put("date",customer.getDate());
            dataList.add(map);
        }

        try(final OutputStream os = response.getOutputStream()){
            ExportUtil.responseSetProperties(fName,response);
            ExportUtil.doExport(dataList,sTitle,mapKey,os);
            return null;
        }catch (Exception e) {
            System.out.println("error");
        }
        return "failure";
    }

    private List<Customer> getData(Integer[] ids) {

        return new ArrayList<Customer>(){{
            add(new Customer(1,"LUOYONG",22,new Date()));
            add(new Customer(2,"LUOYONG2",222,new Date()));
            add(new Customer(3,"LUOYONG3",223,new Date()));
            add(new Customer(4,"LUOYONG4",224,new Date()));
        }};
    }
}
